package com.zyb.lmbackend.runner;

import com.zyb.lmbackend.dto.CategoryStatDto;
import com.zyb.lmbackend.mapper.ClassifyTaskMapper;
import com.zyb.lmbackend.mapper.GoodsBackClassifiedMapper;
import com.zyb.lmbackend.service.BatchClassifierService;
import com.zyb.lmbackend.service.TaxonomyBuilderService;
import java.util.Comparator;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

/**
 * 演示环境启动器：
 * - 自动触发一次归纳与一次分类
 * - 打印最新版本的统计结果
 */
@Component
@Profile("demo")
@RequiredArgsConstructor
@Slf4j
public class DemoRunner implements CommandLineRunner {

    private final TaxonomyBuilderService taxonomyBuilderService;
    private final BatchClassifierService batchClassifierService;
    private final GoodsBackClassifiedMapper classifiedMapper;
    private final ClassifyTaskMapper classifyTaskMapper;

    /** 应用启动后执行演示流程。 */
    @Override
    public void run(String... args) throws Exception {
        log.info("[demo] Step 1: Build taxonomy preview...");
        taxonomyBuilderService.build(200);

        log.info("[demo] Step 2: Start classify task...");
        var task = batchClassifierService.start(200, 4, null);
        log.info("[demo] Task started: id={}, version={}, status={} ", task.getId(), task.getVersion(), task.getStatus());

        // 简单等待一会儿（演示环境数据少，通常很快完成）
        Thread.sleep(2000);

        int latest = Math.max(1, classifyTaskMapper.selectMaxVersion());
        List<CategoryStatDto> rows = classifiedMapper.selectStatsFromView(latest);
        int total = rows.stream().map(r -> r.getCount() == null ? 0 : r.getCount()).reduce(0, Integer::sum);
        rows.forEach(r -> r.setRatio(total > 0 ? r.getCount() * 1.0 / total : 0.0));
        rows.sort(Comparator.comparing(CategoryStatDto::getCount).reversed());

        log.info("[demo] ---- Stats (version={}) ----", latest);
        for (CategoryStatDto r : rows) {
            log.info("code={}, name={}, count={}, ratio={}", r.getCode(), r.getName(), r.getCount(), String.format("%.2f", r.getRatio()));
        }
    }
}
